package tools.keytools;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;

import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;

public class UserController {

    private final PublicKey publicKey; // 假设这是从安全地方加载的
    private final PrivateKey privateKey; // 同上

    public UserController() throws Exception {
        // 这里应该替换为实际加载密钥的方式
        KeyPair keyPair = RSAKeyPairGenerator.generateKeyPair();
        this.publicKey = keyPair.getPublic();
        this.privateKey = keyPair.getPrivate();
    }

    public ResponseEntity<String> encryptPhoneNumber(@RequestBody String phoneNumber) {
        try {
            String encryptedPhoneNumber = RSAEncryptor.encrypt(phoneNumber, publicKey);
            return ResponseEntity.ok(encryptedPhoneNumber);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Encryption failed");
        }
    }

    public ResponseEntity<String> decryptPhoneNumber(@RequestBody String encryptedPhoneNumber) {
        try {
            String decryptedPhoneNumber = RSAEncryptor.decrypt(encryptedPhoneNumber, privateKey);
            return ResponseEntity.ok(decryptedPhoneNumber);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Decryption failed");
        }
    }


    public static void main(String[] args) throws Exception {
        KeyPair keyPair = RSAKeyPairGenerator.generateKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();

        String phoneNumber = "18912345678";
        String encryptedPhoneNumber = RSAEncryptor.encrypt(phoneNumber, publicKey);
        String decryptedPhoneNumber = RSAEncryptor.decrypt(encryptedPhoneNumber, privateKey);

        System.out.println("phoneNumber: " + phoneNumber);
        System.out.println("encryptedPhoneNumber: " + encryptedPhoneNumber);
        System.out.println("decryptedPhoneNumber: " + decryptedPhoneNumber);

    }
}